from flask import Blueprint, request, g, current_app
from flask_app.common.before_request import get_request_data
from flask_app.common.result import false_return, true_return
from flask_app.models.user import User
from flask_app.api import handle_error
from .user import verify_user
from flask_app.common.before_request import get_request_data, get_border
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature, SignatureExpired


token_blueprint = Blueprint("token_blueprint", __name__, url_prefix='/token')

__author__ = '叶伟伟'


@token_blueprint.route('', methods=['POST'])
def get_token():
    # 拿到数据验证用户
    success, user = verify_user(request)
    if not success:
        return false_return(user)

    # Token
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(user.uid,
                                user.username,
                                user.role_id,
                                expiration)
    t = {
        'token': token.decode('ascii')
    }
    return true_return("token生成成功", t)

@token_blueprint.route('/secret', methods=['POST'])
def get_token_info():
    """获取令牌信息"""
    success, data = get_request_data(request, ['token'])
    if not success:
        return false_return(data)
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(data['token'], return_header=True)
    except SignatureExpired:
        return false_return('token is expired')
    except BadSignature:
        return false_return('token is invalid')

    # r = {
    #     # 'uid': data[0]['uid'],
    #     # 'username': data[0]['username'],
    #     # 'role_id': data[0]['role_id'],
    #     'create_at': data[1]['iat'],
    #     'expire_in': data[1]['exp'],
    # }
    target_user = User.get_by_id(data[0]['uid'])
    # r['user'] = target_user.to_json()

    return true_return('获取令牌信息成功', target_user.to_json())

def generate_auth_token(uid, username, role_id,
                        expiration=7200):
    """生成令牌"""
    s = Serializer(current_app.config['SECRET_KEY'],
                   expires_in=expiration)
    return s.dumps({
        'uid': uid,
        'username': username,
        'role_id':role_id
    })

